﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using hedefgrup.reports.renault.definitions;
using hedefgrup.reports.renault;
using hedefgrup.reports.renault.calculators;
using hedefgrup.reports.renault.implementation;
using hedefgrup.reports.renault.date;
using System.Collections.Generic;

public partial class hierarchicResults : reportPage
{
    private const string SUMMARY_TABLE_HEADER_CELL_TEMPLATE = "<td width='30%' height=18px align=center class=t_head >{0}</td>";
    private const string SUMMARY_TABLE_VALUE_CELL_TEMPLATE = "<td width='70%' height=18px align='left' class=vktxt8 >{0}</td>";
    private const string REPORT_TABLE_HEADER_CELL_TEMPLATE = "<td width={0}px height=38px align=center class=t_head valign=center>{1}</td>";
    private const string REPORT_ROW_TEMPLATE = "<tr onmouseover='show(this)' onmouseout='sout(this)' >{0}</td>";
    private const string REPORT_CELL_TEMPLATE = "<td style='text-align:right;' class=vktxt8 >{0}</td>";
    private const string REPORT_IMPORTANT_CELL_TEMPLATE = "<td style='text-align:right;' class=vktxt9 >{0}</td>";
    private const string REPORT_CELL_LEFT_ALIGNED_TEMPLATE = "<td class=vktxt8 >{0}</td>";

    protected override string getReportFileName()
    {
        return "RAPOR - " + base.getReportFileName();
    }

    protected static string getCellTemplate(reportRowDefinition row, optionDefinition opt)
    {
        return
            opt != null && row.getAttributeByName("io") == opt.getValue().ToString()
            ||
            opt == null && row.getAttributeByName("i") == "true"
            ?
                REPORT_IMPORTANT_CELL_TEMPLATE
            :
                REPORT_CELL_TEMPLATE
        ;
    }

    private static string generateReportTableHeaderCell(string text, int width)
    {
        return string.Format(REPORT_TABLE_HEADER_CELL_TEMPLATE, width, text);
    }

    private static string generateReportTableHeaderCell(questionDefinition questionToReport, int width)
    {
        return generateReportTableHeaderCell(questionToReport.getCode() + " - " + questionToReport.getName(), width);
    }

    private string generateReportTableRow(reportDealerInfo dealerInfo, calculatorType calculationType, int order)
    {
        if (dealerInfo.data.baseCount <= 0) return string.Empty;

        List<string> userDealerCodes = new List<string>(base.getUserDealerCodes());
        if (userDealerCodes.Count == 0 || userDealerCodes.Contains(dealerInfo.dealer.getCode()) || dealerInfo.dealer.isParentOfAny(base.getUserDealerCodes()))
        {
            StringBuilder htmlBuilder = new StringBuilder();

            htmlBuilder.AppendFormat(REPORT_CELL_LEFT_ALIGNED_TEMPLATE, order);
            htmlBuilder.AppendFormat(REPORT_CELL_LEFT_ALIGNED_TEMPLATE, dealerInfo.dealer.getCode());
            htmlBuilder.AppendFormat(REPORT_CELL_LEFT_ALIGNED_TEMPLATE, dealerInfo.dealer.getName());

            reportDefinition reportDef = base.getDataCache().reportDefinitions["parental"];

            foreach (reportRowDefinition row in reportDef.rowDefinitions)
            {
                switch (row.getRowType())
                {
                    case "percentage_of_option_yearly_avg":
                        string questionCode = row.getQuestionToReport();
                        int optionValue = Convert.ToInt32(row.getAttributeByName("o"));

                        reportMonth startMonthOfAverage = new reportMonth(base.selectedMonth.getAsDateTime().AddMonths(-11));
                        reportMonth endMonthOfAverage = base.selectedMonth;
                        reportDealerInfo dlrInfo = base.getCalculator().generateReportDataForSingleDealer(dealerInfo.dealer, calculationType, startMonthOfAverage, endMonthOfAverage);

                        htmlBuilder.AppendFormat(getCellTemplate(row, null), (100 * dlrInfo.data.questions[questionCode].calculateOptionPercentage(optionValue)).ToString("0.0"));
                        break;
                    case "base":
                        htmlBuilder.AppendFormat(getCellTemplate(row, null), dealerInfo.data.baseCount);
                        break;
                    default:
                        double value = 0;
                        question questionToReport = dealerInfo.data.questions[row.getQuestionToReport()];
                        switch (row.getRowType())
                        {
                            case "percentage_of_option": value = questionToReport.calculateOptionPercentage(Convert.ToInt32(row.getAttributeByName("o"))); break;
                            case Global.PROJECT_QVN: value = questionToReport.calculateQvn(); break;
                            case "formula_1": value = questionToReport.calculateFormula1(); break;
                            case "formula_2": value = questionToReport.calculateFormula2(); break;
                            case "percentage_over_total_base":
                                string[] optionsToReport = row.getAttributeByName("o").Split(',');
                                foreach (string optionToReportString in optionsToReport)
                                {
                                    int optionToReport = Convert.ToInt32(optionToReportString);
                                    value += questionToReport.getOptionCount(optionToReport);
                                }
                                value = value / (double)dealerInfo.data.baseCount;
                                break;
                        }
                        htmlBuilder.AppendFormat(getCellTemplate(row, null), (value * 100).ToString("0.0"));
                        break;
                }
            }

            return string.Format(REPORT_ROW_TEMPLATE, htmlBuilder);
        }
        return "";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureUserIsLoggedIn();

        excelReportName.Text = base.getReportFileName();

        excelExportDiv.Visible = !IsExcelDownloadRequest;

        string dealerTypeCodes = "[dealer][branch][connected_point][satellite]";
        bool isDealer = base.targetDealer != null ? dealerTypeCodes.Contains("[" + base.targetDealer.getTypeCode() + "]") : false;
        bool isCoordinator = base.targetDealer != null ? base.targetDealer.getTypeCode() == "coordinator" : false;
        bool isArea = base.targetDealer != null ? base.targetDealer.getTypeCode() == "area" : false;

        string dealerRepresentation = base.targetDealer != null ? base.targetDealer.getCode() + " - " + base.targetDealer.getName() : "";

        StringBuilder htmlBuilder = new StringBuilder();

        htmlBuilder.Append(generateReportTableHeaderCell("Sr", 10));
        htmlBuilder.Append(generateReportTableHeaderCell("Kod", 40));
        htmlBuilder.Append(generateReportTableHeaderCell("Tanım", 220));

        reportDefinition reportDef = base.getDataCache().reportDefinitions["parental"];

        foreach (reportRowDefinition row in reportDef.rowDefinitions)
        {
            switch (row.getRowType())
            {
                case "percentage_of_option_yearly_avg":
                    string rowHeader = row.getQuestionToReport() + " - " + base.getDataCache().questionDefinitions[row.getQuestionToReport()].getName();
                    htmlBuilder.Append(generateReportTableHeaderCell(rowHeader + " - 12 Aylık Ortalama", 75));
                    break;
                case "base":
                    htmlBuilder.Append(generateReportTableHeaderCell("Baz", 75));
                    break;
                case "percentage_over_total_base":
                    htmlBuilder.Append(generateReportTableHeaderCell(row.getAttributeByName("h"), 75));
                    break;
                default:
                    htmlBuilder.Append(generateReportTableHeaderCell(base.getDataCache().questionDefinitions[row.getQuestionToReport()], 120));
                    break;
            }
        }

        reportTableHeaderHtml.Text = htmlBuilder.ToString();

        htmlBuilder = new StringBuilder();

        reportDealerInfo[] dealersToReport = base.getCalculator().generateReportDataForMultipleDealers(targetDealer, calculationType, base.selectedMonth - (cumulativeMonths - 1), base.selectedMonth);

        int order = 1;
        foreach (reportDealerInfo dlr in dealersToReport)
        {
            htmlBuilder.Append(generateReportTableRow(dlr, calculationType, order));
            order++;
        }
        reportTableHtml.Text = htmlBuilder.ToString();

        base.RenderComplete();
        renderTime.Text = base.getElapsedRenderTime().ToString();

    }
}
